#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2017-07-01 13:49:03
# @Author  : Your Name (you@example.org)
# @Link    : http://example.org
# @Version : $Id$

''' 获取pm25数据和pm25_24h小时数据
    字段：city_name, city_code,
    '''
import time
import json
import requests

import MySQLdb as msdb
from flask import Flask

app = Flask(__name__)


pos_pm25 = {}  # PM2.5实时数据

cityList = ['wuhan', 'huangshi', 'shiyan', 'jingzhou', 'yichang',
            'jingmen', 'ezhou', 'xiaogan', 'huanggang', 'xianning',
            'suizhou', 'enshizhou', 'xiangyang']

coor_list = [
    [30.58021825, 114.3813259],
    [30.564366, 114.2658559],
    [30.61624898, 114.2942882],
    [30.54143575, 114.3093671],
    [30.62416066, 114.3866026],
    [30.50523194, 114.228482],
    [30.59240691, 114.311796],
    [30.52047321, 114.3920876],
    [30.63934431, 114.1416751],
    [30.29995375, 113.8784635],
    [30.23059000, 115.07272],
    [30.27338000, 114.84820],
    [30.17270000, 114.952425],
    [30.2066600000, 114.9014300000],
    [30.1548800000, 114.9977300000],
    [32.5056200000, 111.0965700000],
    [32.6480200000, 110.7860800000],
    [32.6611500000, 110.9908800000],
    [32.5681430000, 110.8890940000],
    [112.25461, 30.316766],
    [112.2149885, 30.35659058],
    [112.2886, 30.31095],
    [30.71899585, 111.313579],
    [30.70374086, 111.311342],
    [30.65073765, 111.3673618],
    [30.69927541, 111.2747222],
    [30.77609041, 111.3329567],
    [31.0452700000, 112.2061700000],
    [30.9730300000, 112.2071500000],
    [31.0352200000, 112.2266600000],
    [31.0354600000, 112.1994500000],
    [31.0366000000, 112.1946900000],
    [31.0375700000, 112.1954800000],
    [30.3908500000, 114.8949500000],
    [30.3705500000, 114.9020800000],
    [30.4108800000, 114.8398500000],
    [30.9251100000, 113.9244300000],
    [30.9181200000, 113.6934700000],
    [30.4459000000, 114.8981500000],
    [30.4713500000, 114.9080500000],
    [30.4467300000, 114.8869400000],
    [29.4277900000, 114.7018700000],
    [29.8414600000, 114.3170700000],
    [29.8526900000, 114.2988200000],
    [29.8677500000, 114.3339200000],
    [31.7270900000, 113.3649000000],
    [31.6905900000, 113.3806700000],
    [31.7228310000, 113.3809540000],
    [30.2945000000, 109.5026100000],
    [30.2757200000, 109.4807600000],
    [32.0160570000, 112.1579990000],
    [32.0523100000, 112.1498000000],
    [32.1121200000, 112.1893400000],
    [32.0855500000, 112.2042700000]
]


# 数据库取数据
def conn_db(host, user, psd, db):
    _conn = msdb.connect(host, user, psd, db)

    return _conn


# 获取当前时间
def get_time():
    # 记录当前时间
    ct = time.localtime(time.time())
    currentTime = str(ct.tm_year)+str(ct.tm_mon)+str(ct.tm_mday)
    currentHour = ct.tm_hour

    return currentTime, currentHour


# 加载数据
def load_data_from_db(dataType, y, h):
    data = []
    db = conn_db('localhost', 'root', '0000', 'pm25')
    cur = db.cursor()
    sql = "SELECT %s FROM pm25tab WHERE year=%s AND hour=%s" % (dataType, y, h)
    try:
        cur.execute(sql)
        # 获取所有记录列表
        results = cur.fetchall()
        if(len(results) == 0):
            return '暂无数据'
        else:
            for res in results[0]:
                data.append(res)
            return data

    except Exception as e:
        print e
        db.rollback()


# 实时数据
def get_pm25(pm25_type):
    name_lsit = []
    val_list = []
    pm25data = []
    for city in cityList:
        url = 'http://www.pm25.in/api/querys/pm2_5.json?city=' + \
            city + '&token=FN6jrgq1p2y14xYGX8pD'  # 5j1znBVAsnSf5xQyNQyq 测试用
        try:
            resource = requests.get(url)
            res_json_list = resource.json()
            for r in res_json_list:
                name = r['position_name']
                if (name):
                    val = r[pm25_type]
                    val_list.append(val)
                    name_lsit.append(name.encode("utf-8"))
                else:
                    continue
        except requests.ConnectionError as e:
            print e
        except requests.HTTPError as e:
            print e

    for i in range(0, len(coor_list)):
        pos_pm25 = {}
        pos_pm25['name'] = name_lsit[i]
        pos_pm25['value'] = val_list[i]
        pos_pm25['position'] = coor_list[i]
        pm25data.append(pos_pm25)
    return pm25data


# 实时pm25数据
@app.route('/pm25')
def load_p25():
    obj = []
    obj = get_pm25("pm2_5")
    obj = json.dumps(obj, ensure_ascii=False)  #
    return obj


# 实时pm25 24小时数据
@app.route('/pm2524')
def load_pm2524():
    obj = []
    obj = get_pm25("pm2_5_24h")
    obj = json.dumps(obj, ensure_ascii=False)  #
    return obj


# 历史pm25数据
@app.route('/pm25/<int:year>/<int:hour>')
def load_p25_history(year, hour):
    obj = load_data_from_db('pm25', year, hour)
    return ",".join(obj)


# 历史pm25_24小时数据
@app.route('/pm2524/<int:year>/<int:hour>')
def load_p2524_history(year, hour):
    obj = load_data_from_db('pm2524', year, hour)
    return ",".join(obj)


if __name__ == '__main__':

    app.run('0.0.0.0')
